<?php
/**
* Scans for new movies
* @params $_GET[what] movies (so far)
**/
include 'autoload.php';

switch ( $_GET['what'] )
{
    case 'movies':
    {
        $supportedExtensions = array( 'mkv', 'avi', 'iso' );

        $library = new weebUILibrary( 1 );
        $tags = $library->tags();

        $res = $library->query( "SELECT item_location FROM items WHERE {$tags['tag_VolumeName']} LIKE 'KARMACOMA'" );
        while( $row = sqlite_fetch_array( $res ) )
        {
            $libraryFiles[] = basename( $row['item_location'] );
        }

        $dir = "\\\\Belgarion\\Movies";
        if ( !@$directoryHandle = opendir( $dir ) )
            throw new Exception( "Unable to open directory '$dir'" );

        while ( $file = readdir( $directoryHandle ) )
        {
            if ( $file == '..' or $file == '.' )
                continue;
            if ( in_array( pathinfo( $file, PATHINFO_EXTENSION ), $supportedExtensions ) )
            {
                $files[] = $file;
            }
        }
        //exec( 'dir /b \\\\belgarion\\movies', $files );
        $newFiles = array_diff( $files, $libraryFiles );
        $date = date( 'd/m/Y' );
        foreach ( $newFiles as $newFile )
        {
            $location = "x:\\$newFile";
            $itemName = sqlite_escape_string( pathinfo( $newFile, PATHINFO_FILENAME ) );
            $itemLocation = sqlite_escape_string( $location );
            $itemExtID = sqlite_escape_string( strtolower( $location ) ) ;
            $fileSize = sqlite_escape_string( sprintf("%u", filesize( "\\\\Belgarion\\Movies\\$newFile" ) ) );
            $query = "INSERT INTO items (item_name, item_ext_id, item_location, {$tags['tag_Filesize']}, {$tags['tag_VolumeName']}, {$tags['tag_Created']} ) " .
                     "VALUES( '$itemName', '$itemExtID', '$itemLocation', '$fileSize', 'KARMACOMA', '$date' )";
            $library->insertQuery( $query );
            echo "Added '$newFile'<br />";
        }
    } break;
}
?>